package com.tuantuan.common.exception;

import com.alibaba.fastjson.JSON;
import com.tuantuan.common.base.common.CommonErrorCode;
import com.tuantuan.common.base.result.ApiController;
import com.tuantuan.common.base.result.Responses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author wangqinmin
 * @date 2018/08/05
 */
@ControllerAdvice
@RestController
public class GlobalExceptionHandler extends ApiController {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 非法参数验证异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public Responses<Object> handleMethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        List<String> list = new ArrayList<>();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            list.add(fieldError.getDefaultMessage());
        }
        Collections.sort(list);
        logger.error("fieldErrors" + JSON.toJSONString(list));
        return failed(CommonErrorCode.PARAMETER_EXCEPTION, ex.getMessage());
    }

    /**
     * 数据库字段，数据不唯一异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public Responses<Object> handleMethodArgumentNotValidExceptionHandler(SQLIntegrityConstraintViolationException ex) {
        //logger.error("SQLIntegrityConstraintViolationException:", ex);
        logger.error("SQLIntegrityConstraintViolationException:", ex.getMessage());
        return failed(CommonErrorCode.DATABASE_FILED_UNIQUE_EXCEPTION, ex.getMessage());
    }

    /**
     * SQL异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public Responses<Object> handleMethodArgumentNotValidExceptionHandler(SQLException ex) {
        logger.error("SQLException:", ex.getMessage());
        return failed(CommonErrorCode.DATABASE_SQL_EXCEPTION, ex.getMessage());
    }

//    /**
//     * 默认的异常处理
//     *
//     * @param exception
//     * @return
//     */
//    @ExceptionHandler(value = Exception.class)
//    @ResponseStatus(HttpStatus.OK)
//    public Responses<Object> exceptionHandler(Exception exception) {
//        logger.error("exception:", exception);
//        return failed(CommonErrorCode.SYSTEM_EXCEPTION);
//    }

    /**
     * HTTP 请求参数解析异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.OK)
    public Responses<Object> httpMessageNotReadableException(Exception exception) {
        logger.error("httpMessageNotReadableException:", exception);
        return failed(CommonErrorCode.PARAMETER_PARSE_EXCEPTION, exception.getMessage());
    }

    /**
     * HTTP 请求媒体类型不支持异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = HttpMediaTypeNotSupportedException.class)
    @ResponseStatus(HttpStatus.OK)
    public Responses<Object> httpMessageNotReadableException(HttpMediaTypeNotSupportedException exception) {
        logger.error("HttpMediaTypeNotSupportedException:", exception);
        return failed(CommonErrorCode.HTTP_MEDIA_TYPE_EXCEPTION, exception.getMessage());
    }

    //
//    /**
//     * 系统登录异常处理
//     *
//     * @param exception
//     * @return
//     */
//    @ExceptionHandler(value = SysLoginException.class)
//    @ResponseStatus(HttpStatus.OK)
//    public ResponseResult sysLoginExceptionHandler(SysLoginException exception) {
//        logger.warn("系统登录异常:" + exception.getMessage());
//        return new ResponseResult(500, exception.getMessage());
//    }
//
//    /**
//     * 系统登录异常处理
//     *
//     * @return
//     */
//    @ExceptionHandler(value = IncorrectCredentialsException.class)
//    @ResponseStatus(HttpStatus.OK)
//    public ResponseResult incorrectCredentialsExceptionHandler(IncorrectCredentialsException exception) {
//        logger.warn("系统登录异常状态：[{}]", "用户名或密码错误");
//        return new ResponseResult(500, exception.getMessage());
//    }
//
//    /**
//     * 业务层异常处理
//     *
//     * @param exception
//     * @return
//     */
//    @ExceptionHandler(value = BusinessException.class)
//    @ResponseStatus(HttpStatus.OK)
//    public Responses<Object> businessExceptionHandler(BusinessException exception) {
//        StackTraceElement[] stackTraceElements = exception.getStackTrace();
//        String exceptionMsg = "businessException:" + exception.getMessage() + ":" + stackTraceElements[0].toString();
////        logger.error(AnsiUtil.getAnsi(Ansi.Color.RED, exceptionMsg), exception);
//        Integer code = exception.getCode();
//        code = (code == null ? CommonConstant.BUSINESS_EXCEPTION : code);
//        return Responses.
//        return new ResponseResult(code, exception.getMessage());
//    }
//

}
